<script setup>
import { ref, onMounted, nextTick } from "vue"; // 添加 nextTick
import * as echarts from "echarts";
import "echarts-extension-amap";
import mapJson from "./map.json";

const chartRef = ref(null); // 将 chartRef 移到顶层

// 模拟数据
const mapData = [
  { name: "渝北区", value: 3, category1: 3, category2: 3 },
  // 其他区域数据...
];
const option = {
  tooltip: {
    trigger: "item",
    formatter: (params) => {
      return `${params.name}<br/>类别一：${
        params.data?.category1 || 0
      }个<br/>类别二：${params.data?.category2 || 0}个`;
    },
  },
  visualMap: {
    min: 0,
    max: 5,
    left: "5%",
    bottom: "5%",
    calculable: true,
    seriesIndex: [0],
    inRange: {
      color: ["#0C2E79", "#0444AD", "#0665FF"],
    },
    textStyle: {
      color: "#fff",
    },
  },
  geo: {
    map: "重庆",
    label: {
      show: true,
      color: "#fff",
      fontSize: 12,
    },
    itemStyle: {
      areaColor: "#0C2E79",
      borderColor: "#0665FF",
      borderWidth: 1,
    },
    emphasis: {
      itemStyle: {
        areaColor: "#0444AD",
        shadowBlur: 10,
        shadowColor: "rgba(6, 101, 255, 0.5)",
      },
    },
  },
  series: [
    {
      name: "风险指数",
      type: "map",
      geoIndex: 0,
      data: mapData,
    },
  ],
};

// 添加点击事件处理函数
const handleMapClick = (params) => {
  const regionName = params.name;
  const regionData = mapData.find((data) => data.name === regionName);
  if (regionData) {
    showModal.value = true;
    selectedRegion.value = regionData;
  }
};

onMounted(async () => {
  // 加载重庆地图数据
  // const { data: mapJson } = await fetch(
  //   "https://geo.datav.aliyun.com/areas_v3/bound/500000_full.json"
  // ).then((res) => res.json());

  echarts.registerMap("重庆", mapJson);

  // 确保地图数据加载完成后再初始化图表
  if (mapJson) {
    await nextTick(); // 确保 DOM 已经更新
    initChart(option);
  }

  // 添加点击事件监听
  // const myChart = echarts.getInstanceByDom(chartRef.value);
  // myChart.on("click", handleMapClick);
});

// 弹窗状态管理
const showModal = ref(false);
const selectedRegion = ref(null);

function initChart(option) {
  // const chartRef = ref(null); // 从这里移除
  if (chartRef.value) { // 确保 chartRef.value 存在
    const chart = echarts.init(chartRef.value);
    chart.setOption(option);
    chart.on("click", handleMapClick);
  } else {
    console.error("Chart container not found");
  }
}
</script>

<template>
  <div class="mapchart">
    <div ref="chartRef" class="chart-container"></div>
  </div>
</template>

<style scoped>
.chart-container {
  width: 100%; /* 或者具体的像素值，例如 600px */
  height: 500px; /* 或者具体的像素值 */
}
.mapchart {
  width: 800px;
  height: 800px;
}
</style>
